package com.kingschan.jeasytag.web.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.kingschan.jeasytag.HttpQueryBean;
import com.kingschan.jeasytag.container.EasyTagContainer;
import com.kingschan.jeasytag.container.impl.EasyTagContainerImpl;
import com.kingschan.jeasytag.sql.JdbcTemplete;
import com.kingschan.jeasytag.sql.query.BuilderSqlQueryBean;
import com.kingschan.jeasytag.sql.query.Pagination;
import com.kingschan.jeasytag.sql.query.Query;
import com.kingschan.jeasytag.sql.query.QueryFactory;
import com.kingschan.jeasytag.sql.query.SqlQueryBean;
import com.kingschan.jeasytag.sql.sqlparse.GenericSelectParse;
import com.kingschan.jeasytag.tag.power.DIYTag;
import com.kingschan.util.bean.BeanUtil;
import com.kingschan.util.excel.jxl.ExcelOutput;
import com.kingschan.util.lang.StringUtil;

@WebServlet(name="GridServlet",urlPatterns="/jeasytag/grid")
public class GridServlet extends HttpServlet{
	private static Logger log = Logger.getLogger(GridServlet.class);
	private static final long serialVersionUID = 1L;
	private EasyTagContainer container=EasyTagContainerImpl.getInstance();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
		String model = req.getParameter("c");
		String diy=req.getParameter("diy");		
		try {
			if (null!=diy) {
				diy(req, resp, diy);
			}
			if ("e".equals(StringUtil.ConvertNullStr(model))) {
				export(req,resp);				
			}else {
				query(req,resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		
		
	}
	
	
	public void diy(HttpServletRequest req, HttpServletResponse resp,String diy)throws Exception{
		
		String path=container.getSerializationPath().concat(diy.concat(".data"));
		Class<?> c;
		DIYTag dt = (DIYTag) BeanUtil.DesSerializationObject(path);
		c=Class.forName(dt.getClassname().trim());
		//Class<?> margs[] = new Class<?>[3];
		//Method m = c.getMethod(dt.getMethod(),margs);
	
		Method[] ms = c.getMethods();
		for (Method method : ms) {
			if (method.getName().equals(dt.getMethod())) {
				//method.invoke(c, diy,req,resp,null);
				System.out.println("返回类型:"+method.getReturnType().getSimpleName());
				 Type[] paramTypeList = method.getGenericParameterTypes();// 方法的参数列表
				 System.out.println("参数个数："+paramTypeList.length);
		            for (Type paramType : paramTypeList) {
		                System.out.println(" 参数类型: " + paramType);// 参数类型
		                System.out.println(paramType instanceof HttpServletRequest);
		            }
			}
		}
	}
	
	
	/**
	 * query model
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	public void query(HttpServletRequest req, HttpServletResponse resp)throws Exception{
		HttpQueryBean hqb = new HttpQueryBean(req, resp);
		SqlQueryBean sqb =new BuilderSqlQueryBean(hqb).buliderSqlQueryBean();
		Pagination pagination =null;
		String product="{\"total\":0,\"rows\":[]}";	
		if (null==hqb.getPageindex()||null==hqb.getPagesize()) {
			// simple query 
			GenericSelectParse sp = new GenericSelectParse(sqb.getSql_command(),sqb.getDbtype());
			sp.setOrderby(sqb.getOrder_by());
			sp.appendWhere(sqb.getWhere_str());
			log.debug("the query request is simple query >>SQL:"+sp.toString());
			List<Map<String, Object>> data = JdbcTemplete.getListBySql(sqb.getConnection(), sp.toString(), true);
			pagination = new Pagination();
			pagination.setData(data);
			pagination.setTotal(data.size());
		}else{
			// pagination query
			
			Query q = QueryFactory.getQuery(sqb.getDbtype());
			pagination=q.paginationQuery(sqb.getConnection(),
					sqb.getSql_command()
					, sqb.getPage_index()
					, sqb.getPage_size()
					, sqb.getOrder_by()
					, true
					, sqb.getWhere_str());
			
		}
		product=pagination.FormatPageJsonData();
		resp.setContentType("text/html;charSet=gbk");
		PrintStream ps = new PrintStream(resp.getOutputStream());
		ps.print(product);
	}
	/**
	 * export excel model
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	public void export(HttpServletRequest req, HttpServletResponse resp)throws Exception{
		HttpQueryBean hqb = new HttpQueryBean(req, resp);
		SqlQueryBean sqb =new BuilderSqlQueryBean(hqb).buliderSqlQueryBean();
		String filename=StringUtil.getDecriptCode(hqb.getHttpargs().get("filename"),container.getApplictionKey()).concat(".xls");
		String [] title=java.net.URLDecoder.decode(hqb.getHttpargs().get("title"), "utf-8").split(",");
		String disableCloums[]=StringUtil.getDecriptCode(hqb.getHttpargs().get("disablecloums"),container.getApplictionKey()).split(",");
		Set<String> set = new HashSet<String>();
		for (String s : disableCloums) {
			set.add(s);
		}
		String wherestr="";
		GenericSelectParse sp = new GenericSelectParse(sqb.getSql_command(),sqb.getDbtype());
		if (null!=hqb.getCondition()) {	
			log.debug(" condition export ");
			sp.appendWhere(sqb.getWhere_str());
		}else{
			log.debug(" choose export ");
			wherestr=" and "+hqb.getHttpargs().get("choosefield")+" in ("+hqb.getHttpargs().get("ids")+")";
			sp.appendWhere(wherestr);
		}
		log.debug(" export sql command :  "+sp.toString());
		List<?> list = JdbcTemplete.queryForList(sqb.getConnection(), sp.toString(), true, set);
		InputStream excelData = new ExcelOutput().exportExcel(title, list);
		resp.setCharacterEncoding("UTF-8"); 
		resp.setContentType("application/vnd.ms-excel;charset=UTF-8");
		resp.addHeader("Content-Disposition","attachment;filename=\""+filename+"\"");
	    ServletOutputStream sos = resp.getOutputStream();
        byte[] b= new byte[1024];
        while (excelData.read(b, 0, 1024)!=-1) {
			sos.write(b);						
		}
        sos.flush();
        sos.close();
	}
}
